package com.liangxy.news.database;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Query;
import androidx.room.Transaction;

import com.liangxy.news.model.News;
import com.liangxy.news.model.UserHistory;

import java.util.List;

/**
 * DAO for user browsing history
 */
@Dao
public interface HistoryDao {
    
    /**
     * Insert a news item into user's browsing history
     * @param userId User ID
     * @param newsId News ID
     */
    @Query("INSERT OR REPLACE INTO user_history (user_id, news_id, timestamp) VALUES (:userId, :newsId, strftime('%s', 'now'))")
    void insert(String userId, String newsId);
    
    /**
     * Get user history record by user ID and news ID
     * @param userId User ID
     * @param newsId News ID
     * @return UserHistory object if found, null otherwise
     */
    @Query("SELECT * FROM user_history WHERE user_id = :userId AND news_id = :newsId LIMIT 1")
    UserHistory getUserHistoryByUserAndNews(String userId, String newsId);
    
    /**
     * Get user's browsing history
     * @param userId User ID
     * @return LiveData list of news
     */
    @Transaction
    @Query("SELECT n.* FROM news n INNER JOIN user_history h ON n.uniquekey = h.news_id " +
            "WHERE h.user_id = :userId ORDER BY h.timestamp DESC LIMIT 50")
    LiveData<List<News>> getUserHistory(String userId);
    
    /**
     * Delete user's browsing history
     * @param userId User ID
     */
    @Query("DELETE FROM user_history WHERE user_id = :userId")
    void deleteUserHistory(String userId);
}